<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="所属账号" prop="account">
                <el-input v-model.trim="queryParams.account" placeholder="请输入所属账号" clearable style="width: 240px"
                          @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="站点信息" prop="keyWord">
                <el-input v-model.trim="queryParams.keyWord" placeholder="id / 域名 / 名称" clearable style="width: 240px"
                          @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="套餐类型" prop="packageName">
                <el-select v-model="queryParams.packageName" placeholder="套餐类型" clearable style="width: 240px">
                    <el-option v-for="dict in packageNameDict" :key="dict.value" :label="dict.label"
                               :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button v-if="false" type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                           v-hasPermi="['system:role:export']"
                >导出
                </el-button>
            </el-col>
            <right-toolbar v-if="false" :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="siteList">
            <el-table-column type="index" width="55" align="center">
                <template slot-scope="scope">
                    {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="所属账号" prop="account.account" width="120"/>
            <el-table-column label="站点id" prop="siteId" width="120"/>
            <el-table-column label="站点名称" prop="siteName" :show-overflow-tooltip="true" min-width="150"/>
            <el-table-column label="站点域名" prop="siteDomain" :show-overflow-tooltip="true" min-width="150"/>
            <el-table-column label="站定发布状态" prop="siteStatus" align="center" width="100"/>
            <el-table-column label="站点套餐类型" prop="packageName" align="center" width="100"/>
            <el-table-column label="套餐到期时间" align="center" prop="packageExpiryDate" width="180">
                <template slot-scope="scope">
                        <span v-if="scope.row.packageName === '站点尊享版'"
                        >{{ parseTime(scope.row.packageExpiryDate, '{y}-{m}-{d}') }}
                            <el-tag type="warning"
                                    v-if="getExpireDays(scope.row.packageExpiryDate)>7 && getExpireDays(scope.row.packageExpiryDate)<=30"
                            >近期到期</el-tag>
                            <el-tag type="danger" v-if="getExpireDays(scope.row.packageExpiryDate)<7 && getExpireDays(scope.row.packageExpiryDate) >= 0">即将到期</el-tag>
                            <el-tag type="danger" v-if="getExpireDays(scope.row.packageExpiryDate)<0">已过期</el-tag>
                        </span>
                </template>
            </el-table-column>
            <el-table-column label="同步时间" prop="createTime" align="center" width="180">
                <template slot-scope="scope">
                    {{ scope.row.updateTime ? parseTime(scope.row.updateTime) : parseTime(scope.row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="280">
                <template slot-scope="scope" v-if="scope.row.roleId !== 1">
                    <el-button size="mini" type="text" icon="el-icon-refresh" @click="handleSync(scope.row)">同步站点</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改域名</el-button>
                    <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
                        <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="handleCheckBan" icon="el-icon-document-delete"
                                              >检测封禁</el-dropdown-item>
                            <el-dropdown-item command="handleUpdateContent" icon="el-icon-refresh"
                                             >更新页面</el-dropdown-item>
                            <el-dropdown-item command="handleUpdateSiteName" icon="el-icon-refresh"
                                             >修改名称</el-dropdown-item>
                            <el-dropdown-item command="handleQueryHistory" icon="el-icon-notebook-2"
                                              >查看历史</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList"
        />

        <el-dialog :title="updateType === 'domain' ?'快站域名修改' : '站点名称修改'" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="updateDomainForm" :model="form" label-width="80px" :rules="rule" @submit.native.prevent>
                <el-form-item label="快站域名"  prop="siteDomain" v-if="updateType === 'domain'">
                    <el-input placeholder="请输入内容" v-model="form.siteDomain">
                        <template slot="prepend">https://</template>
                        <template slot="append">.kuaizhan.com</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="站点名称" v-if="updateType === 'siteName'">
                    <el-input placeholder="请输入站点名称" v-model="form.siteName"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitEditDomain">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog title="更新页面" :visible.sync="updateOpen" append-to-body>
            <el-form ref="updateContentForm" :model="updateForm" :rules="updateFormRule" label-width="100px" @submit.native.prevent>
                <el-form-item label="当前内容">
                    <el-input autosize type="textarea" placeholder="请输入内容" disabled v-model="updateForm.curContent"></el-input>
                </el-form-item>
                <el-form-item label="更新内容" prop="siteContent">
                    <el-input :autosize="{ minRows: 5 }" type="textarea" placeholder="填写网络地址(eg：https://prd.h5.gylm315.cn/kuaizhan)会获取该地址下的html内容更新到此快站，填写非网络地址会将填写内容直接更新到快站" v-model="updateForm.siteContent"></el-input>
                    <div v-for="item in gyDomains" :key="item.env">
                        {{item.env}}环境：{{item.url}} <el-button type="text" @click="updateForm.siteContent = item.url">填入</el-button>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitUpdateContent">确 定</el-button>
                <el-button @click="cancelUpdateContent">取 消</el-button>
            </div>
        </el-dialog>

        <el-drawer
            title="修改历史"
            :visible.sync="historyDrawer">
            <div  v-infinite-scroll="loadHistory"
                  infinite-scroll-distance="3"
                  :infinite-scroll-disabled="disableLoad" style="padding-right: 40px; overflow-y: auto; height: 100%;">
                <el-timeline>
                    <el-timeline-item v-for="(item, index) in siteHistory" :key="index" :timestamp="`${item.updateType == '1' ? '域名' : '内容'}更新 ${parseTime(item.createTime)}`" placement="top">
                        <el-card>
                            <div style="word-break: break-all; max-height: 500px; overflow-y: auto;">{{item.updateContent}}</div>
                            <el-divider><i class="el-icon-top"></i></el-divider>
                            <div style="word-break: break-all; max-height: 500px; overflow-y: auto;">{{item.beforeContent}}</div>
                        </el-card>
                    </el-timeline-item>
                </el-timeline>
            </div>
        </el-drawer>
    </div>
</template>
<script>
import { siteList, siteEdit, checkBan, siteSync, getContent, siteHistory} from '@/api/kzManage'
import { Loading } from 'element-ui';
export default {
    name: 'Site',
    components: {},
    computed: {
        disableLoad() {
            return this.historyLoading || this.historyFinish
        }
    },
    data() {
        return {
            packageNameDict: [
                { label: '全部', value: '' },
                { label: '尊享版', value: '站点尊享版' },
                { label: '免费版', value: '站点免费版' }
            ],
            showSearch: true,
            queryParams: {
                account: '',
                keyWord: '',
                packageName: '站点尊享版',
                pageNum: 1,
                pageSize: 20
            },
            dateRange: [],
            loading: false,
            total: 0,
            siteList: [],
            open: false,
            updateType: 'domain',
            form: {},
            rule: {
                siteDomain: [
                    { required: true, message: '域名不能为空', trigger: 'blur' },
                    { pattern: /^[a-zA-Z0-9-]+$/, message: '站点域名只能包含字母、数字、连字符（\'-\'）', trigger: 'change' },
                ],
                siteName: [
                    { required: true, message: '站点名称不能为空', trigger: 'blur' },
                ]
            },
            updateOpen: false,
            updateForm: {},
            updateFormRule: {
                siteContent: [
                    { required: true, message: '更新内容不能为空', trigger: 'change' },
                ]
            },
            historyDrawer: false,
            siteHistory: [],
            historyQuery: {
                pageNum: 1,
                pageSize: 10
            },
            historyLoading: false,
            historyFinish: false,
            gyDomains: [
                {env: 'test', url: 'https://txtsth5.gylm315.cn/kuaizhan'},
                {env: 'stg', url: 'https://txstgh5.gylm315.cn/kuaizhan'},
                {env: 'prd', url: 'https://prd.h5.gylm315.cn/kuaizhan'},
            ]
        }
    },
    created() {
        this.getList()
    },
    mounted() {
    },
    beforeDestroy() {
    },
    methods: {
        getList() {
            this.loading = true
            siteList(this.queryParams).then((res) => {
                this.siteList = res.data.list
                this.total = res.data.total
            }).finally(() => {
                this.loading = false
            })
        },
        handleQuery() {
            this.loading = true
            this.queryParams.pageNum = 1
            siteList(this.queryParams).then(res => {
                this.siteList = res.data.list
                this.total = res.data.total
            }).finally(() => {
                this.loading = false
            })
        },
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case 'handleUpdateContent':
                    this.handleUpdateContent(row);
                    break;
                case 'handleQueryHistory':
                    this.handleQueryHistory(row);
                    break;
                case 'handleCheckBan':
                    this.handleCheckBan(row);
                    break;
                case 'handleUpdateSiteName':
                    this.handleUpdateSiteName(row);
                    break;
                default:
                    break;
            }
        },
        handleUpdate(row) {
            this.updateType = 'domain'
            this.form = {
                siteId: row.siteId,
                siteDomain: this.getSubdomain(row.siteDomain)
            }
            this.open = true
        },
        handleUpdateSiteName(row) {
            this.updateType = 'siteName'
            this.form = {
                siteId: row.siteId,
                siteName: row.siteName
            }
            this.open = true
        },
        submitEditDomain() {
            this.$refs['updateDomainForm'].validate(valid => {
                if (valid) {
                    siteEdit(this.form).then(res => {
                        this.$message.success('操作成功')
                        this.open = false
                        this.getList()
                    })
                }
            })
        },
        handleCheckBan(row) {
            let loadingInstance = Loading.service({ text: '正在检测中，请稍候', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' });
            checkBan(row).then(res => {
                if (res.data.isBannedWX) {
                    this.$notify.error({
                        title: '域名已被微信封禁',
                        message: '请及时更换域名'
                    });
                } else {
                    this.$notify({
                        title: '检测成功',
                        message: '域名正常',
                        type: 'success'
                    });
                }
            }).finally(() => {
                loadingInstance.close()
            })
        },
        handleSync(row) {
            let loadingInstance = Loading.service({ text: '正在同步中，请稍候', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' });
            siteSync(row).then(res => {
                this.$message.success(res.msg)
                this.getList()
            }).finally(() => {
                loadingInstance.close()
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            if (this.$refs.menu != undefined) {
                this.$refs.menu.setCheckedKeys([])
            }
            (this.menuExpand = false),
                (this.menuNodeAll = false),
                (this.deptExpand = true),
                (this.deptNodeAll = false),
                (this.form = {
                    roleId: undefined,
                    roleName: undefined,
                    roleKey: undefined,
                    roleSort: 0,
                    status: '0',
                    menuIds: [],
                    deptIds: [],
                    menuCheckStrictly: true,
                    deptCheckStrictly: true,
                    remark: undefined
                })
            this.resetForm('updateDomainForm')
            this.resetForm('updateContentForm')
        },
        handleExport() {

        },
        getSubdomain(url) {
            const regex = /^(?:https?:\/\/)?([a-z0-9-]+)\.[a-z0-9-]+\.[a-z]+$/i
            const matches = url.match(regex)
            return matches ? matches[1] : ''
        },
        getExpireDays(date) {
            if (!date) {
                return 0
            }
            const oneDay = 24 * 60 * 60 * 1000 // 一天的毫秒数
            const firstDate = new Date(date) // 创建第一个日期对象
            const secondDate = new Date() // 创建第二个日期对象
            // 计算两个日期之间的天数差值
            const diffDays = Math.round((firstDate - secondDate) / oneDay)
            return diffDays
        },

        handleUpdateContent(row) {
            getContent(row).then(res => {
                this.updateForm = {
                    siteId: row.siteId,
                    curContent: res.data,
                    siteContent: ''
                }
                this.reset()
                this.updateOpen = true
            })
        },
        submitUpdateContent() {
            this.$refs['updateContentForm'].validate(valid => {
                if (valid) {
                    siteEdit(this.updateForm).then(res => {
                        this.$message.success('操作成功')
                        this.updateOpen = false
                    })
                }
            })
        },
        cancelUpdateContent() {
            this.updateOpen = false
            this.reset()
        },
        handleQueryHistory(row) {
            this.historyQuery.siteId = row.siteId
            this.historyQuery.pageNum = 1
            this.siteHistory = []
            this.historyFinish = false
            this.historyDrawer = true
            this.loadHistory()
        },
        loadHistory() {
            this.historyLoading = true
            siteHistory(this.historyQuery).then(res => {
                let list = res.data.list || []
                if (this.historyQuery.pageNum === 1) {
                    this.siteHistory = []
                }
                this.siteHistory = this.siteHistory.concat(list)
                if (this.siteHistory.length >= res.data.total) {
                    this.historyFinish = true
                } else {
                    this.historyQuery.pageNum++
                }
            }).finally(() => {
                this.historyLoading = false
            })
        }
    }
}
</script>

<style scoped lang="scss">
</style>
